<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="人员类别" prop="userType">
        <el-select v-model="queryParams.userType" placeholder="请选择人员类别" clearable>
          <el-option v-for="dict in user_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="用户账号" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户账号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="车牌号" prop="licensePlate">
        <el-input v-model="queryParams.licensePlate" placeholder="请输入车牌号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable>
          <el-option v-for="dict in check" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['vehicle:check:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['vehicle:check:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['vehicle:check:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['vehicle:check:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="审核ID" align="center" prop="registerId" />
      <el-table-column label="人员类别" align="center" prop="userType">
        <template #default="scope">
          <dict-tag :options="user_type" :value="scope.row.userType" />
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="姓名" align="center" prop="nickName" />
      <el-table-column label="用户账号" align="center" prop="userName" />
      <el-table-column label="车牌号" align="center" prop="licensePlate" />
      <el-table-column label="联系电话" align="center" prop="phonenumber" />
      <el-table-column label="审核状态" align="center" prop="status">
        <template #default="scope">
          <div :class="getStatusClass(scope.row.status)">
            <dict-tag :options="check" :value="scope.row.status" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleDetail(scope.row)"
            v-hasPermi="['vehicle:ebike:query']">审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改车辆审核对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="checkRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="人员类别" prop="userType">
          <el-select v-model="form.userType" placeholder="请选择人员类别">
            <el-option v-for="dict in user_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item label="归属部门" prop="deptId">
          <el-tree-select v-model="form.deptId" :data="deptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属部门"
            check-strictly />
        </el-form-item>
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="form.licensePlate" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="车辆图片" prop="vehicleImage">
          <image-upload v-model="form.vehicleImage" />
        </el-form-item>
        <el-form-item label="车架号" prop="frameNumber">
          <el-input v-model="form.frameNumber" placeholder="请输入车架号" />
        </el-form-item>
        <el-form-item label="购入日期" prop="purchaseDate">
          <el-date-picker clearable v-model="form.purchaseDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择购入日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="电瓶生产日期" prop="batteryProductionDate">
          <el-date-picker clearable v-model="form.batteryProductionDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择电瓶生产日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="电瓶有效期" prop="batteryExpiryDate">
          <el-date-picker clearable v-model="form.batteryExpiryDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择电瓶有效期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核车辆详情对话框 -->
    <el-dialog title="审核详情" v-model="detailOpen" width="500px" append-to-body>
      <el-form ref="checkRef" :model="form" :rules="rules" label-width="100px" class="form-container">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="人员类别">
              <dict-tag :options="user_type" :value="form.userType" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="部门">
              {{ form.deptName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="姓名">
              {{ form.nickName }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="学号">
              {{ form.userName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="联系电话">
              {{ form.phonenumber }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="购入日期">
              {{ formatDate(form.purchaseDate) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="车牌号">
              {{ form.licensePlate }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="车架号">
              {{ form.frameNumber }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="电瓶生产日期">
              {{ formatDate(form.batteryProductionDate) }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="电瓶有效期">
              {{ formatDate(form.batteryExpiryDate) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="车辆图片">
              <img :src="form.vehicleImage" alt="车辆图片" style="width: 100%; max-height: 300px;" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitApprove">通 过</el-button>
          <el-button type="danger" @click="showRejectDialog">不通过</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 不通过理由对话框 -->
    <el-dialog :title="'不通过理由'" v-model="rejectOpen" width="500px" append-to-body>
      <el-form :model="rejectForm" :rules="rejectRules" ref="rejectRef" label-width="100px" class="custom-form">
        <el-form-item label="不通过理由" prop="reason" class="custom-form-item">
          <el-input v-model="rejectForm.reason" type="textarea" :rows="4" placeholder="请输入不通过的理由"
            @input="updateRemainingChars" class="custom-textarea" />
          <p class="remaining-chars">还可输入 {{ remainingChars }} 字</p>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer custom-footer">
          <el-button type="primary" @click="submitRejectForm">确 认</el-button>
          <el-button @click="cancelReject">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Check">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { listCheck, getCheck, delCheck, addCheck, updateCheck, deptTreeSelect } from "@/api/vehicle/check";
import { addEbike } from "@/api/vehicle/ebike";
import dayjs from 'dayjs';

const { proxy } = getCurrentInstance();
const { user_type, check } = proxy.useDict('user_type', 'check');

const checkList = ref([]);
const open = ref(false);
const detailOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref(undefined);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickName: null,
    userName: null,
    licensePlate: null,
    status: null,
  },
  rules: {
    userType: [
      { required: true, message: "人员类别不能为空", trigger: "change" }
    ],
    nickName: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    userName: [
      { required: true, message: "用户账号不能为空", trigger: "blur" }
    ],
    licensePlate: [
      { required: true, message: "车牌号不能为空", trigger: "blur" }
    ],
    phonenumber: [
      { required: true, message: "联系电话不能为空", trigger: "blur" }
    ],
    vehicleImage: [
      { required: true, message: "车辆图片不能为空", trigger: "blur" }
    ],
    purchaseDate: [
      { required: true, message: "购入日期不能为空", trigger: "blur" }
    ],
  },
  rejectOpen: false, // 控制不通过理由对话框的显示
  rejectForm: {
    reason: ''
  },
  rejectRules: {
    reason: [
      { required: true, message: '请输入不通过的理由', trigger: 'blur' },
      { max: 500, message: '最多输入500个字符', trigger: 'blur' }
    ]
  },
  remainingChars: 500 // 剩余可输入字符数
});

const { queryParams, form, rules, rejectOpen, rejectForm, rejectRules, remainingChars } = toRefs(data);
/** 查询车辆审核列表 */
function getList() {
  loading.value = true;
  listCheck(queryParams.value).then(response => {
    checkList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  detailOpen.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    registerId: null,
    deptId: null,
    nickName: null,
    userName: null,
    licensePlate: null,
    phonenumber: null,
    vehicleImage: null,
    frameNumber: null,
    purchaseDate: null,
    batteryProductionDate: null,
    batteryExpiryDate: null,
    status: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("checkRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.registerId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加车辆审核";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _registerId = row.registerId || ids.value
  getCheck(_registerId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改车辆审核";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["checkRef"].validate(valid => {
    if (valid) {
      if (form.value.registerId != null) {
        updateCheck(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCheck(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _registerIds = row.registerId || ids.value;
  proxy.$modal.confirm('是否确认删除车辆审核编号为"' + _registerIds + '"的数据项？').then(function () {
    return delCheck(_registerIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('vehicle/check/export', {
    ...queryParams.value
  }, `check_${new Date().getTime()}.xlsx`)
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

/** 查看审核详情操作 */
function handleDetail(row) {
  reset();
  const _registerId = row.registerId;
  getCheck(_registerId).then(response => {
    form.value = response.data;
    detailOpen.value = true;
  });
}

async function submitApprove() {
  try {
    // 设置审核状态为已通过
    form.value.status = '1';

    // 格式化日期
    const formattedCreateTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
    const formattedUpdateTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');

    // 调用添加车辆信息接口
    await addEbike({
      userName: form.value.userName,
      licensePlate: form.value.licensePlate,
      vehicleImage: form.value.vehicleImage,
      points: 0, // 初始记分为0
      frameNumber: form.value.frameNumber,
      batteryProductionDate: form.value.batteryProductionDate,
      batteryExpiryDate: form.value.batteryExpiryDate,
      delFlag: '0',
      createTime: formattedCreateTime,
      updateTime: formattedUpdateTime,
      createBy: form.value.createBy,
      updateBy: form.value.updateBy,
      remark: form.value.remark
    });

    // 调用删除审核记录接口
    await delCheck(form.value.registerId);

    // 成功提示
    ElMessage.success("审核通过");
    detailOpen.value = false;
    getList();
  } catch (error) {
    console.error("审核通过失败", error);
    ElMessage.error("审核通过失败，请稍后再试");
  }
}

/** 显示不通过理由对话框 */
function showRejectDialog() {
  rejectOpen.value = true;
  rejectForm.value.reason = ''; // 重置不通过理由
  remainingChars.value = 500; // 重置剩余字符数
}

/** 更新剩余字符数 */
function updateRemainingChars(value) {
  remainingChars.value = 500 - value.length;
}

/** 提交不通过理由 */
function submitRejectForm() {
  proxy.$refs.rejectRef.validate((valid) => {
    if (valid) {
      form.value.status = '2'; // 设置审核状态为未通过
      form.value.remark = rejectForm.value.reason; // 将不通过理由存入备注
      updateCheck(form.value).then(response => {
        ElMessage.success("审核不通过");
        detailOpen.value = false;
        rejectOpen.value = false;
        getList();
      });
    }
  });
}

/** 取消不通过理由 */
function cancelReject() {
  rejectOpen.value = false;
  rejectForm.value.reason = ''; // 重置不通过理由
  remainingChars.value = 500; // 重置剩余字符数
}

// 获取审核状态的样式类
function getStatusClass(status) {
  switch (status) {
    case '0': // 未审核
      return 'unaudited';
    case '1': // 已通过
      return 'approved';
    case '2': // 未通过
      return 'unapproved';
    default:
      return '';
  }
}

// 格式化日期
function formatDate(date) {
  return dayjs(date).format('YYYY-MM-DD');
}

getDeptTree();
getList();
</script>

<style scoped>
/* 未审核 */
.unaudited {
  border: 1px solid gray;
  padding: 2px 3px;
  border-radius: 4px;
}

/* 未通过 */
.unapproved {
  border: 1px solid red;
  padding: 2px 3px;
  border-radius: 4px;
  color: red;
}

/* 已通过 */
.approved {
  border: 1px solid green;
  padding: 2px 3px;
  border-radius: 4px;
  color: green;
}
</style>